package com.liusaidh.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liusaidh.domain.Comment;
import com.liusaidh.domain.Like;
import com.liusaidh.domain.PageBean;
import com.liusaidh.domain.User;
import com.liusaidh.mapper.BlogMapper;
import com.liusaidh.mapper.UserMapper;
import com.liusaidh.service.UserService;
import com.liusaidh.utils.AesEncryptorUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;

import static com.liusaidh.utils.RandomUtil.getRandomUser;
import static com.liusaidh.utils.RegexUtils.isEmailInvalid;
import static com.liusaidh.utils.RegexUtils.isPasswordInvalid;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private BlogMapper blogMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 获取验证码
     *
     * @param email
     * @return
     */
    @Override
    public String getEmailRegister(String email) {
        //1.先判断邮箱是否存在
        int time = 5;
        String code = RandomUtil.randomString(6);
        String content = "<p>【V视界】 尊敬的" + email + "用户：</p>" +
                "<p>您正在进行申请注册账号的服务，如本人操作，请勿泄露该验证码！</p>" +
                "<p> 验证码为：<b style = 'font-size:20px;color:blue;'>" + code + "</b></p>" +
                "<p>注意：有效时间为 " + time + " 分钟</p>"
                + "<p>注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证帐户安全\n" +
                "（工作人员不会向你索取此验证码，请勿泄漏！)</p>";
        MailUtil.send(email, "邮箱注册验证码", content, true);
        return code;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }



    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public long getTotalCount(String condition) {
        return userMapper.getTotalCount(condition);
    }

    @Override
    public PageBean getAllUser(Integer pageNo, Integer pageSize, String condition) {
//        long totalCount = userMapper.getTotalCount(condition);
//        int pageMaxSize = (int)totalCount / pageSize;
//        if (pageNo < 0){
//            pageNo = 1;
//        }
//        if (totalCount % pageSize == 0){
//            if (pageNo > pageMaxSize){
//                pageNo = pageMaxSize;
//            }
//        }else {
//            if (pageNo > pageMaxSize + 1){
//                pageNo = pageMaxSize + 1;
//            }
//        }
//        pageSize = pageSize > 0 ? pageSize : 10;
        PageHelper.startPage(pageNo,pageSize);
        List<User> allUser = userMapper.getAllUser(condition);
        Page<User> page =  (Page<User>)allUser;
        return new PageBean(page.getTotal(), page.getResult());
    }

    @Override
    public int banUserToComment(Integer id) {
        return userMapper.banUserToComment(id);
    }

    @Override
    public int notBanUserToComment(Integer id) {
        return userMapper.notBanUserToComment(id);
    }

    @Override
    public void concernUser(Integer id, Integer id1) {
        userMapper.concernUser(id, id1);
    }

    @Override
    public void notConcernUser(Integer id, Integer id1) {
        userMapper.notConcernUser(id, id1);
    }

    @Override
    public List<User> getUserByLike(String condition) {
        return userMapper.getUserByLike(condition);
    }

    @Override
    public boolean judgeUserOfConnection(Integer myId, Integer otherId) {
        return blogMapper.judgeUserOfConnection(myId, otherId) == 1;
    }


    @Override
    public List<Comment> getOthersCommentOfMe(Integer id, Integer pageNo, Integer pageSize) {
        return userMapper.getOthersCommentOfMe(id,(pageNo - 1)*pageSize,pageSize);
    }


    @Override
    public List<Like> getOthersLikeOfMe(Integer id, Integer pageNo, Integer pageSize) {
        return userMapper.getOthersLikeOfMe(id,(pageNo - 1)*pageSize,pageSize);
    }

    @Override
    public int addUser(User user) {
        user.setUsername("user_" + new Random().nextInt(1000000000));
        user.setEntryDate(LocalDate.now().toString());
        user.setAvatarUrl("https://weibo-img.oss-cn-beijing.aliyuncs.com/defaultAvatar.png");
        return userMapper.addUser(user);
    }

    @Override
    public int deleteUserById(Integer id) {
        return userMapper.deleteUserById(id);
    }


    @Override
    public User getUserInfoByEmail(String email) {
        return userMapper.getUserInfoByName(email);
    }

    @Override
    public ModelAndView register(String code, String email, String password, HttpSession session) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("email", email);
        mav.addObject("pwd", password);
        mav.addObject("code", code);
        if (isEmailInvalid(email)) {
            mav.addObject("msg", "邮箱格式不合法！");
            mav.setViewName("register");
            return mav;
        }
        if (isPasswordInvalid(password)) {
            mav.addObject("msg", "密码格式不合法！大小写字母和数字组成8~16位");
            mav.setViewName("register");
            return mav;
        }
        if (userMapper.isExitEmail(email) != null) {
            mav.addObject("msg", "该邮箱已经被注册！");
            mav.setViewName("register");
            return mav;
        } else {
            if (session.getServletContext().getAttribute("code").equals(code) && session.getServletContext().getAttribute("email").equals(email)) {
                userMapper.addUser(getRandomUser(email,password));
                mav.addObject("msg", "注册成功！！");
                mav.setViewName("login");
                return mav;
            } else {
                mav.addObject("msg", "邮箱或验证码错误！");
                mav.setViewName("register");
                return mav;
            }
        }
    }

    @Override
    public ModelAndView login(String email, String password, HttpSession session) {
        ModelAndView mav = new ModelAndView();
        User user = userMapper.getUserByEmailAndPassword(email,  AesEncryptorUtil.encrypt(password));
        if (userMapper.isExitEmail(email) == null) {
            mav.addObject("msg", "该账号还未注册，请先注册！");
            mav.setViewName("register");
            return mav;
        }
        if (user == null) {
            mav.setViewName("login");
            mav.addObject("msg", "登录失败，请检查邮箱或密码是否正确");
            mav.addObject("email", email);
            return mav;
        }
        if (user.getIsManager() == 1) {
            mav.setViewName("redirect:/user/userList");
            session.setAttribute("id", user.getId());
            session.setAttribute("username",user.getUsername());
            return mav;
        }
        if (user.getIsManager() == 0) {
            session.setAttribute("id", user.getId());
            mav.addObject("msg", "登录成功");
            mav.setViewName("redirect:/blog/getMyConnectionBlog");
        }
        return mav;
    }

}
